package com.example.studentknowledge.service;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Favorite;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.repository.FavoriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 收藏服务类
 */
@Service
@Transactional
public class FavoriteService {
    
    @Autowired
    private FavoriteRepository favoriteRepository;
    
    @Autowired
    private ArticleService articleService;
    
    /**
     * 添加收藏
     */
    public Favorite addFavorite(User user, Article article) {
        // 检查是否已经收藏
        if (favoriteRepository.existsByUserAndArticle(user, article)) {
            throw new RuntimeException("已经收藏过该文章");
        }
        
        Favorite favorite = new Favorite();
        favorite.setUser(user);
        favorite.setArticle(article);
        
        Favorite savedFavorite = favoriteRepository.save(favorite);
        
        // 更新文章收藏数
        articleService.updateFavoriteCount(article.getId());
        
        return savedFavorite;
    }
    
    /**
     * 取消收藏
     */
    public void removeFavorite(User user, Article article) {
        Optional<Favorite> favorite = favoriteRepository.findByUserAndArticle(user, article);
        if (favorite.isPresent()) {
            favoriteRepository.delete(favorite.get());
            
            // 更新文章收藏数
            articleService.updateFavoriteCount(article.getId());
        }
    }
    
    /**
     * 切换收藏状态
     */
    public boolean toggleFavorite(User user, Article article) {
        Optional<Favorite> favorite = favoriteRepository.findByUserAndArticle(user, article);
        
        if (favorite.isPresent()) {
            // 已收藏，取消收藏
            favoriteRepository.delete(favorite.get());
            articleService.updateFavoriteCount(article.getId());
            return false;
        } else {
            // 未收藏，添加收藏
            addFavorite(user, article);
            return true;
        }
    }
    
    /**
     * 检查用户是否收藏了文章
     */
    public boolean isFavorited(User user, Article article) {
        return favoriteRepository.existsByUserAndArticle(user, article);
    }
    
    /**
     * 获取用户的收藏列表
     */
    public Page<Favorite> getUserFavorites(User user, Pageable pageable) {
        return favoriteRepository.findByUserOrderByCreatedAtDesc(user, pageable);
    }
    
    /**
     * 获取文章的收藏列表
     */
    public Page<Favorite> getArticleFavorites(Article article, Pageable pageable) {
        return favoriteRepository.findByArticleOrderByCreatedAtDesc(article, pageable);
    }
    
    /**
     * 统计用户的收藏数
     */
    public Long countByUser(User user) {
        return favoriteRepository.countByUser(user);
    }
    
    /**
     * 统计文章的收藏数
     */
    public Long countByArticle(Article article) {
        return favoriteRepository.countByArticle(article);
    }
    
    /**
     * 根据ID查找收藏
     */
    public Optional<Favorite> findById(Long id) {
        return favoriteRepository.findById(id);
    }
    
    /**
     * 删除收藏
     */
    public void deleteFavorite(Long id) {
        Favorite favorite = favoriteRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("收藏记录不存在"));
        
        favoriteRepository.deleteById(id);
        
        // 更新文章收藏数
        articleService.updateFavoriteCount(favorite.getArticle().getId());
    }
    
    /**
     * 批量删除用户的收藏
     */
    public void deleteUserFavorites(User user) {
        favoriteRepository.deleteByUser(user);
    }
    
    /**
     * 批量删除文章的收藏
     */
    public void deleteArticleFavorites(Article article) {
        favoriteRepository.deleteByArticle(article);
    }
}